package cn.liberals.basic.service.impl;

import cn.liberals.basic.constant.BaseConstants;
import cn.liberals.basic.exception.BusinessException;
import cn.liberals.basic.jwt.JwtUtils;
import cn.liberals.basic.jwt.RsaUtils;
import cn.liberals.basic.jwt.UserInfo;
import cn.liberals.basic.service.ILoginService;
import cn.liberals.basic.utils.*;
import cn.liberals.basic.vo.LoginVo;
import cn.liberals.basic.vo.RegisterVo;
import cn.liberals.basic.vo.WechatVo;
import cn.liberals.system.domain.Menu;
import cn.liberals.system.mapper.MenuMapper;
import cn.liberals.system.mapper.PermissionMapper;
import cn.liberals.user.domain.Logininfo;
import cn.liberals.user.domain.User;
import cn.liberals.user.domain.Wxuser;
import cn.liberals.user.mapper.LogininfoMapper;
import cn.liberals.user.mapper.UserMapper;
import cn.liberals.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    // 使用spel表达式获取到yml里的自定义配置，也就是私钥的文件名称
    @Value("${jwt.rsa.pri}")
    private String jwtRsaPrivate;

    /*
    * @Title: account
    * @Description: 账号密码登录
    * @Author: liberals
    * @Version: 1.0
    * @Date:  2022/7/14 14:58
    * @Parameters:
    * @Return
    */
    @Override
    public Map<String, Object> account(LoginVo loginVo) {
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        String type = loginVo.getType();
        // 参数为空校验
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type)){
            throw new BusinessException("参数不能为空！");
        }
        // 根据账号&type查询用户是否存在，如果不存在抛出异常
        System.out.println(username);
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);
        // 为空则抛出异常
        if (logininfo == null) {
            throw new BusinessException("参数不能为空");
        }

        // 3.判断加盐加密之后的密码是否一致，如果不一致抛出异常
        String passwordTmp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        // 如果不一致则抛出异常
        if (!logininfo.getPassword().equals(passwordTmp)) {
            throw new BusinessException("用户名或密码错误请重新输入");
        }
        // 生成UUID作为token放到redis中设置有效时间为30分钟
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//
//        // 将用户敏感信息置为空
//        logininfo.setPassword("");
//        logininfo.setSalt("");
//
//        // 设置token和用户信息到map中
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("token", token);
//        map.put("logininfo",logininfo);

        return loginSuccessJwtHandler(logininfo);
    }

    /**
     * @Title: loginSuccessJwtHandler
     * @Description: 用户登录成功后生成JWT加密串并放入到map对象中
     * @Author: liberals
     * @Version: 1.0
     * @Date:  2022/7/15 13:23
     * @Parameters: [cn.liberals.user.domain.Logininfo]
     * @Return java.util.Map<java.lang.String,java.lang.Object>
     */
    public Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo){
        // 5.获取私钥进行加密
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPrivate).getFile());
        // 8.将uuid&&logininfo存入到map中，返回给前端
        Map<String, Object> map = new HashMap<>();

        // 6.根据Logininfo&menus&permissions加密之后得到JWT串
        UserInfo userInfo = new UserInfo();
        if (logininfo.getType() == 0){
            // 1.如果是后台用户那么需要设置菜单权限和按钮权限到userInfo中
            List<String> permissions = permissionMapper.loadOwnPermissionByLogininfoId(logininfo.getId());
            List<Menu> menus = menuMapper.loadOwnMenuByLogininfoId(logininfo.getId());
            userInfo.setPermissions(permissions);
            userInfo.setMenus(menus);
            map.put("permissions", permissions);
            map.put("menus", menus);
        }
        userInfo.setLogininfo(logininfo);
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 60 * 24);

        // 7.把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");

        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;
    }

    /*
    * @Title: loginMobileVerificationCode
    * @Description: 手机验证码登录
    * @Author: liberals
    * @Version: 1.0
    * @Date:  2022/7/14 14:58
    * @Parameters:
    * @Return
    */
    @Override
    public Map<String, Object> loginMobileVerificationCode(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String smsCodeValue = loginVo.getSmsCodeValue();
        String type = loginVo.getType();
        // 1.判断参数合法性
        if (phone==null){
            throw new BusinessException("手机号为空！");
        }
        if (!ValidateUtil.validatePhone(phone)){
            throw new BusinessException("请输入有效的手机号！");
        }
        // 2.判断两次手机号是否一致
        String phoneCodeKey = BaseConstants.verifyCodeConstant.BUSINESS_LOGIN_KEY +":"+phone;
        String phoneCodeValue = redisTemplate.opsForValue().get(phoneCodeKey).toString();
        String phoneCode = phoneCodeValue.split(":")[1];
        if (StringUtils.isEmpty(phoneCodeValue)){
            throw new BusinessException("验证码错误！");
        }

        // 3.判断验证码是否输入正确
        if (!phoneCode.equalsIgnoreCase(smsCodeValue)){
            throw new BusinessException("验证码错误！");
        }
        // 4.判断loginInfo是否有这个用户
        Logininfo logininfo = logininfoMapper.loadByPhoneAndType(loginVo);
        if (logininfo==null){
            throw new BusinessException("该用户不存在，请重新输入！");
        }
        // 正确，把信息存入redis，设置30分钟有效
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("token",token);
        redisTemplate.opsForValue().set("loginInfo",logininfo);
        // 5.把token封装到map中（UUID）
        // 6.处理敏感信息，再put logininfo到map中
        logininfo.setSalt("");
        logininfo.setPassword("");
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("loginInfo",logininfo);
        return map;
    }

    /*
    * @Title: wechat
    * @Description: 微信登录接口，根据code获取accessToken
    * @Author: liberals
    * @Version: 1.0
    * @Date:  2022/7/10 18:18
    * @Parameters:
    * @Return
    */
    @Override
    public AjaxResult wechat(WechatVo wechatVo) {
        String code = wechatVo.getCode();
        // 1.判断参数是否为空
        if(StringUtils.isEmpty(wechatVo.getCode())){
            throw new BusinessException("参数为空，请重新传递！");
        }
        // 2.拼接二步曲请求地址，获取access_token、openid
        String tokenUrl = BaseConstants.WechatConstant.TOKEN_URL
                .replace("APPID", BaseConstants.WechatConstant.APPID)
                .replace("SECRET", BaseConstants.WechatConstant.SECRET)
                .replace("CODE", code);
        // 3.发起请求获取到JSON字符串
        String jsonStr = HttpUtil.httpGet(tokenUrl);
        // 4.将字符串JSON转换为JSON对象，获取到access_token&openid
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObj.getString("access_token");
        String openId = jsonObj.getString("openid");
        // 5.根据openId查询t_wxuser
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
        // 6.判断微信用户信息是否存在
        if(wxuser != null && wxuser.getUserId() != null){
            // 6.1.wx用户存在并且已经绑定了账号，直接免密登录
            // - 根据wxuser中的userid查询logininfo信息
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            // 生成UUID作为token存入到redis中设置有效期30分钟
//            String token = UUID.randomUUID().toString();
//            redisTemplate.opsForValue().set(
//                    token,
//                    logininfo,
//                    30,
//                    TimeUnit.MINUTES
//            );
//            // 5.将用户敏感信息置空
//            logininfo.setPassword("");
//            logininfo.setSalt("");
//            // 6.并设置token和用户信息到map中
//            HashMap<String, Object> map = new HashMap<>();
//            map.put("token", token);
//            map.put("logininfo", logininfo);
            Map<String, Object> map = loginSuccessJwtHandler(logininfo);
            return AjaxResult.me().setResultObj(map);
        }

        // 3.2.不存在，传递access_token&openId到页面，并且success=false&message=nobinder
        /*new StringBuffer()
                .append("?accessToken=")
                .append(jsonObj.getString("access_token"))
                .append("&openId=")
                .append(jsonObj.getString("openid"));*/
        String paramStr = "?accessToken=" + jsonObj.getString("access_token") + "&openId=" + jsonObj.getString("openid");
        return AjaxResult.me().setSuccess(false).setMessage("nobinder").setResultObj(paramStr);
    }

    @Override
    public void smsCode(RegisterVo vo) {

    }

    /*
    * @Title: binder
    * @Description: 微信登录绑定账号
    * @Author: liberals
    * @Version: 1.0
    * @Date:  2022/7/10 21:26
    * @Parameters:
    * @Return
    */
    @Override
    @Transactional
    public Map<String, Object> binder(WechatVo wxDto) {
        // 1.非空校验
        String verifyCode = wxDto.getVerifyCode();
        String phone = wxDto.getPhone();
        String accessToken = wxDto.getAccessToken();
        String openId = wxDto.getOpenId();
        if (StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)){
            throw new BusinessException("参数异常！");
        }
        // 2.手机验证码校验
        // 为空校验
        String phoneCodeKey = BaseConstants.verifyCodeConstant.BUSINESS_BINDER_KEY + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        // 判断验证码是否正确
        String phoneCode = phoneCodeValueRedis.toString().split(":")[1];
        if (!phoneCode.equalsIgnoreCase(verifyCode)){
            throw new BusinessException("手机验证码错误，请重新输入！");
        }
        // 根据手机号查询用户是否存在
        User user = userMapper.loadByPhone(phone);
        // 不存在：初始化user&logininfo并保存
        Logininfo logininfo = null;
        if (user == null){
            user = smsCodeDto2User(phone);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }else {  // 存在：查询Logininfo
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }
        // 4.根据前端传递的accessToken&openId查询微信用户基本信息
        String wxUserUrl = BaseConstants.WechatConstant.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpUtil.httpGet(wxUserUrl);
        // 5.通过JSONObject方法将JSON字符串转换为指定对象
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        // 6.保存wxUser对象，并且需要设置userId字段为user对象的主键
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        // 7.返回成功登录map
        // 生成UUID作为key
//        String token = UUID.randomUUID().toString();
//        // 将uuid&&logininfo设置到redis中，设置30分钟有效期
//        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//        // 把Logininfo对象的敏感信息置为空，作为value
//        logininfo.setSalt("");
//        logininfo.setPassword("");
//        // 将uuid&&logininfo存入到map中，返回给前端
//        Map<String, Object> map = new HashMap<>();
//        map.put("token", token);
//        map.put("logininfo", logininfo);
        return loginSuccessJwtHandler(logininfo);
    }


    /*
    * @Title: smsCodeDto2User
    * @Description: 初始化user的值
    * @Author: liberals
    * @Version: 1.0
    * @Date:  2022/7/10 23:55
    * @Parameters:
    * @Return
    */
    private User smsCodeDto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + "1");
        user.setPassword(saltPassword);
        user.setSalt(salt);
        // 给用户发个短信，告知他初始密码是多少
        String initPwd = "123456";
        SmsUtils.sendMsg(phone, "亲爱的用户，您的初始密码为：" + initPwd + "请尽快修改密码");
        return user;
    }

    /*
    * @Title: user2Logininfo
    * @Description: 拷贝user的对象信息到logininfo里去
    * @Author: liberals
    * @Version: 1.0
    * @Date:  2022/7/10 23:55
    * @Parameters:
    * @Return
    */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

}
